package com.liyiruo.testMain;

import com.liyiruo.pojo.HelloWorld;
import com.liyiruo.service.UserService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.util.Map;

/**
 * @author liyiruo
 * @Description
 * @Date 2022/3/23 下午4:54
 */
public class MainTest {
    public static void main(String[] args) {
        /**
         * 从classpath目录下获取xml文件
         * ApplicationContext
         */
        ApplicationContext context = new ClassPathXmlApplicationContext("helloword1.xml");
        HelloWorld obj = (HelloWorld) context.getBean("helloWorld0");
        HelloWorld obj1 = (HelloWorld) context.getBean("helloWorld1");
        obj.getMessage();
        obj1.getMessage();


        /**
         * 从classpath目录下获取xml文件
         * AbstractApplicationContext
         */
        AbstractApplicationContext context2 = new ClassPathXmlApplicationContext("helloword2.xml");
        HelloWorld obj2 = (HelloWorld) context2.getBean("helloWorld");
        obj2.getMessage();
        context2.registerShutdownHook();

        /**
         * 从全路径下获取文件 路径开头一个/不能行，//就可以了
         * ApplicationContext
         */
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext("//Users/liyiruo/IdeaProjects/spring/src/main/resources/helloword2.xml");
        HelloWorld helloWorld11 = applicationContext.getBean("helloWorld1", HelloWorld.class);
        helloWorld11.getMessage();
        /**
         * 根据类型获取获取，可能获取多个。key为id Beans.xml
         * 根据key从Map里获取
         */
        Map<String, HelloWorld> beansOfType = applicationContext.getBeansOfType(HelloWorld.class);
        HelloWorld helloWorld = beansOfType.get("helloWorld");
        helloWorld.getMessage();

        //从注解中获取对象
        ApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext("com.liyiruo");
        HelloWorld helloWorld2 = (HelloWorld) annotationConfigApplicationContext.getBean("zhujie");
        int count = annotationConfigApplicationContext.getBeanDefinitionCount();
        System.out.println(count);
        helloWorld2.getMessage();

        BeanFactory factory = new AnnotationConfigApplicationContext("com.liyiruo");
        HelloWorld helloWorld21 = factory.getBean("zhujie", HelloWorld.class);
        helloWorld21.getMessage();


        BeanFactory factory1 = new ClassPathXmlApplicationContext("beans1.xml");
        UserService bean = factory1.getBean(UserService.class);
        System.out.println(bean);
    }
}
